import 'package:common/common.dart';
import 'package:common/export/bloc.dart';
import 'package:common/lara_press_logs.dart';
import 'user_action_history_state.dart';

class LaraPressUserActionHistoryCubit
    extends Cubit<LaraPressUserActionHistoryState> {
  LaraPressUserActionHistoryCubit()
    : super(LaraPressUserActionHistoryState().init());

  Future<void> getSearchHistory() async {
    List<String> searchHistoryList = await LaraPressCommon.keyDb.getStringList(
      'searchHistory',
      defaultValue: [],
    );
    emit(state.copyWith(searchHistory: searchHistoryList));
  }

  // 添加搜索记录
  Future<void> addSearchHistory(String searchHistory) async {
    // 先获取所有搜索记录
    List<String> searchHistoryList = List.from(state.searchHistory);
    // 如果搜索记录中包含当前搜索记录，则删除
    if (searchHistoryList.contains(searchHistory)) {
      searchHistoryList.remove(searchHistory);
    }
    // 将当前搜索记录添加到第一条
    searchHistoryList.insert(0, searchHistory);
    // 设置搜索记录
    emit(state.copyWith(searchHistory: searchHistoryList));
    try {
      await LaraPressCommon.keyDb.setStringList(
        'searchHistory',
        searchHistoryList,
      );
    } catch (e) {
      LaraPressLogs.getInstance().error(
        'addSearchHistory error: $e',
        tag: 'LaraPressUserActionHistoryCubit',
      );
    }
  }
}
